# -*- coding = utf-8 -*-
# @Time    : 2025/3/17 下午8:13
# @Author  : yqk
# @File    : word_cloud.py
# @Software: PyCharm

# import sqlite3
# import jieba
# import matplotlib.pyplot as plt
# from wordcloud import WordCloud
# from PIL import Image
# import numpy as np
#
# conn = sqlite3.connect("movie.db")
# cur = conn.cursor()
# sql = 'select introduction from movie250'
# data = cur.execute(sql)
# text = ""
# for item in data:
#     text = text + item[0].replace("/", "").replace(" ", "").replace("\n", "")
#
# # print(text)
# cur.close()
# conn.close()
#
# cut = jieba.cut(text)
# text = " ".join(cut)
#
# image = Image.open("R-C.png")
# image_array = np.array(image)  #将图片转换为数组
#
# wc = WordCloud(
#     background_color="white",
#     mask=image_array,
#     font_path="simsun.ttc"
# )
# wc.generate_from_text(text)
# fig = plt.figure(1)
# plt.imshow(wc)
# plt.axis("off")
#
# plt.show()  # 显示图像
#
#
#

import sqlite3
import jieba
import matplotlib.pyplot as plt
from wordcloud import WordCloud
from PIL import Image, ImageEnhance
import numpy as np

# 连接数据库并提取数据
conn = sqlite3.connect("movie.db")
cur = conn.cursor()
sql = 'select introduction from movie250'
data = cur.execute(sql)
text = ""
for item in data:
    text = text + item[0].replace("/", "").replace(" ", "").replace("\n", "")

cur.close()
conn.close()

# 使用jieba分词
cut = jieba.cut(text)
text = " ".join(cut)

# 加载背景图片并增强对比度
image = Image.open("R-C.png")

# 将图像转换为灰度图像
image_gray = image.convert("L")

# 增强对比度
enhancer = ImageEnhance.Contrast(image_gray)
image_gray = enhancer.enhance(2)  # 增强对比度，数值越大，效果越明显

# 将灰度图像转换为二值图像，阈值可以调节
threshold = 150  # 阈值可以调整
image_binary = image_gray.point(lambda p: p > threshold and 255)

# 转换为NumPy数组
image_array = np.array(image_binary)

# 创建词云
wc = WordCloud(
    background_color="white",
    mask=image_array,
    font_path="simsun.ttc",
    contour_width=1,  # 设置词云的轮廓宽度
    contour_color="black",  # 设置词云的轮廓颜色
    max_words=200,  # 限制显示最多的词数
    width=800,  # 设置词云的宽度
    height=800  # 设置词云的高度
)

# 生成词云
wc.generate_from_text(text)

# 绘制图像
fig = plt.figure(1)
plt.imshow(wc, interpolation="bilinear")
plt.axis("off")

# 显示图像
plt.show()





